package reflect;

import java.io.File;
import java.net.URISyntaxException;

/**
 * 实例化与当前Test4所在同一个包中的所有类
 */
public class Test4 {
    public static void main(String[] args) throws ClassNotFoundException, URISyntaxException, InstantiationException, IllegalAccessException {
//        Class cls = Class.forName("reflect.Test4");//类名可以输入
//        String packName = cls.getPackage().getName();//根据Test4类对象获取包名
//        File dir = new File(
//                cls.getResource(".").toURI()
//        );

        String packName = Test4.class.getPackage().getName();//根据Test4类对象获取包名
        File dir = new File(
            Test4.class.getResource(".").toURI()
        );
        File[] subs = dir.listFiles(f->f.getName().endsWith(".class"));
        for(File sub : subs){
//            String fileName = sub.getName();
//            String className = fileName.substring(0,fileName.indexOf("."));

            String className = sub.getName().replace(".class","");
            System.out.println(className);
            Class cls = Class.forName(packName+"."+className);
            System.out.println("实例化:"+className);
            Object obj = cls.newInstance();
            System.out.println(obj);
        }
    }
}
